package observer

type ISubject[T any] interface {
	Attach(observer Observer[T])
	Detach(observer Observer[T])
	Notify(msg T)
}

type Subject[T any] struct {
	observers []*Observer[T]
}

// Attach 添加观察者
func (s *Subject[T]) Attach(observer *Observer[T]) {
	s.observers = append(s.observers, observer)
}

func (s *Subject[T]) getIndex(observer *Observer[T]) int {
	for i, ob := range s.observers {
		if ob == observer {
			return i
		}
	}
	return -1
}

// Detach 删除观察者
func (s *Subject[T]) Detach(observer *Observer[T]) {
	index := s.getIndex(observer)
	if index == -1 {
		return
	}
	s.observers = append(s.observers[:index], s.observers[:index+1]...)
}

// Notify 通知所有观察者
func (s *Subject[T]) Notify(msg T) {
	for _, ob := range s.observers {
		ob.Update(msg)
	}
}
